package com.qsxc.system.config.mybatis;

import com.baomidou.mybatisplus.core.enums.SqlMethod;
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.qsxc.constants.Constants;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;

/**
 * 逻辑删除，更新status字段,以及last_updated_by，last_updated_date字段
 *
 * @author
 * 2021-04-07
 */
public class DeleteByIdLogic extends AbstractMethod {

    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        SqlMethod sqlMethod = SqlMethod.UPDATE_BY_ID;
        String additional = this.optlockVersion() + tableInfo.getLogicDeleteSql(true, false);
        StringBuilder builder = new StringBuilder();
        builder.append("<set>\n");
        if (containField(tableInfo, "last_updated_by")) {
            builder.append("last_updated_by=" + Constants.DEFAULT_CREATED_BY + ",\n");
        }
        if (containField(tableInfo, "last_updated_date")) {
            builder.append("last_updated_date=now(),\n");
        }
        if (containField(tableInfo, "status")) {
            builder.append("status=0,\n");
        }
        builder.append("</set>");
        String sql = String.format(sqlMethod.getSql(), tableInfo.getTableName(), builder.toString(),
                tableInfo.getKeyColumn(), "et." + tableInfo.getKeyProperty(), additional);
        SqlSource sqlSource = this.languageDriver.createSqlSource(this.configuration, sql, modelClass);
        return this.addUpdateMappedStatement(mapperClass, modelClass, "deleteByIdLogic", sqlSource);
    }

    private static boolean containField(TableInfo tableInfo, String filedName) {
        for (TableFieldInfo item : tableInfo.getFieldList()) {
            if (item.getColumn().equals(filedName)) {
                return true;
            }
        }
        return false;
    }
}
